package com.wangtianxiang.sxp.dbbase.config.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;

import java.util.Arrays;

abstract class SxpBeanRegister {
	private static final Logger logger = LoggerFactory.getLogger(SxpBeanRegister.class);
	/**
	 * bean for register
	 * @param registry
	 * @param beanNameGenerator
	 * @param name
	 * @param alias can be null
	 * @param annotatedBeanDefinition
	 */
	void registerBean(BeanDefinitionRegistry registry, BeanNameGenerator beanNameGenerator, String name,String[] alias,
					  AnnotatedBeanDefinition annotatedBeanDefinition) {
		Exception exception = null;
		try{
			// 可以自动生成name
			String beanName = (null != name ? name : beanNameGenerator.generateBeanName(annotatedBeanDefinition, registry));
			// bean注册的holer类.
			BeanDefinitionHolder beanDefinitionHolder = new BeanDefinitionHolder(annotatedBeanDefinition, beanName, alias);
			// 使用bean注册工具类进行注册.
			BeanDefinitionReaderUtils.registerBeanDefinition(beanDefinitionHolder, registry);
		}catch (Exception e){
			exception = e;
			throw e;
		}finally {
			logger.info("###### registration for bean[{}] is success?{}, beanClassName[{}], beanAlias[{}].",(exception==null?"true": "false, error: "+ exception.getMessage()), name,annotatedBeanDefinition.getBeanClassName(), Arrays.toString(alias));
		}

	}
}
